<?php

namespace app\controllers;

use core\{Validation, Session};
use app\models\Auth;

class Login extends \core\Controller
{
    // 显示登录表单
    public function index()
    {
        if (isLogged()) {
            return redirect(url('/'));
        }
        
        $this->pageInfo = ['title' => '登录'];
        $this->view('user/login');
    }

    // 登录
    public function check()
    {
        if (strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
            // 检测验证码
            $captcha = $_POST['captcha'];
            if (strtolower($captcha) !== strtolower(session('captcha'))) {
                return json('验证码错误');
            }
            // 表单数据
            $input = [
                'username' => $_POST['username'],
                'password' => $_POST['password'],
            ];
            // 验证规则
            $rules  = [
                'username' => ['required', '3,32',  '姓名应为 3-32 个字符'],
                'password' => ['required', '6,250', '密码应为 6 个字符及以上'],
            ];
            // 验证
            $validate = new Validation($input, $rules);
            $result = $validate->check();

            // 验证不通过
            if (!$result) {
                return json($validate->error);
            }

            $auth = new Auth();

            // 用户不存在
            if (empty($auth->findByName($input['username']))) {
                return json('用户名不存在');
            }

            // 用户存在，开始登录
            $user = $auth->login($input['username'], $input['password']);
            if (!$user) {
                return json('用户名或密码错误');
            }

            // 登录成功，设置 session
            Session::set([
                'user_id'   => $user['id'],
                'user_name' => $user['username'],
            ]);

            return json('登录成功', 'success');
        }
    }

    
    // 退出
    public function logout()
    {
        Session::destroy();
        return redirect(url('/'));
    }
}
